<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true" label-width="80px">
            <el-form-item label="文章标题" prop="title">
              <el-input v-model="queryParams.title" placeholder="请输入标题" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="所属分类" prop="categoryId">
              <el-select v-model="queryParams.categoryId" placeholder="请选择分类" clearable>
                <el-option v-for="item in categoryOptions" :key="item.id" :label="item.title" :value="item.id" />
              </el-select>
            </el-form-item>
            <el-form-item label="状态" prop="status">
              <el-select v-model="queryParams.status" placeholder="请选择状态" clearable>
                <el-option v-for="dict in cms_article_status" :key="dict.value" :label="dict.label" :value="dict.value" />
              </el-select>
            </el-form-item>
            <el-form-item label="推荐类型" prop="isTop">
              <el-select v-model="queryParams.isTop" placeholder="请选择推荐类型" clearable>
                <el-option label="普通" value="0" />
                <el-option label="置顶" value="1" />
                <el-option label="推荐" value="2" />
                <el-option label="置顶且推荐" value="3" />
              </el-select>
            </el-form-item>
            <el-form-item label="创建时间">
              <el-date-picker
                v-model="dateRange"
                type="daterange"
                range-separator="-"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                value-format="YYYY-MM-DD"
              />
            </el-form-item>
            <el-form-item label="内容类型" prop="modelType">
              <el-select v-model="queryParams.modelType" placeholder="请选择内容类型" clearable>
                <el-option v-for="item in modelTypeOptions" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['cms:article:add']">新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate()" v-hasPermi="['cms:article:edit']">修改</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete()" v-hasPermi="['cms:article:remove']"
              >删除</el-button
            >
          </el-col>
          <el-col :span="1.5">
            <el-button type="warning" plain icon="Download" @click="handleExport" v-hasPermi="['cms:article:export']">导出</el-button>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table v-loading="loading" :data="articleList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="类型" align="center" width="100">
          <template #default="scope">
            {{ modelTypeOptions.find((item) => item.value === scope.row.modelType)?.label || '-' }}
          </template>
        </el-table-column>
        <el-table-column label="所属分类" align="center" prop="categoryId">
          <template #default="scope">
            {{ categoryOptions.find((item) => item.id === scope.row.categoryId)?.title }}
          </template>
        </el-table-column>
        <el-table-column label="作者" align="center" prop="author" />
        <el-table-column label="发布时间" align="center" prop="publishTime" width="180">
          <template #default="scope">
            <span>{{ parseTime(scope.row.publishTime, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="推荐类型" align="center" width="100">
          <template #default="scope">
            <el-tag v-if="scope.row.isTop === '1'" type="danger">置顶</el-tag>
            <el-tag v-else-if="scope.row.isTop === '2'" type="success">推荐</el-tag>
            <el-tag v-else-if="scope.row.isTop === '3'" type="warning">置顶且推荐</el-tag>
            <el-tag v-else type="info">普通</el-tag>
          </template>
        </el-table-column>

        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-tooltip content="修改" placement="top">
              <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['cms:article:edit']"></el-button>
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['cms:article:remove']"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getList" />
    </el-card>
    <!-- 添加或修改CMS文章对话框 -->
    <el-dialog :title="dialog.title" v-model="dialog.visible" width="800px" append-to-body>
      <el-form ref="articleFormRef" :model="form" :rules="rules" label-width="100px">
        <!-- 添加模型类型选择 -->
        <el-form-item label="内容类型" prop="modelType">
          <el-select v-model="form.modelType" placeholder="请选择内容类型" @change="handleModelTypeChange" :disabled="form.id !== undefined">
            <el-option v-for="item in modelTypeOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>

        <!-- 基础信息 -->
        <el-form-item label="URL别名" prop="slug">
          <el-input v-model="form.slug" placeholder="请输入URL别名" />
        </el-form-item>
        <el-form-item label="所属分类" prop="categoryId">
          <el-select v-model="form.categoryId" placeholder="请选择文章分类" clearable class="w-[100%]">
            <el-option v-for="item in categoryOptions" :key="item.id" :label="item.title" :value="item.id" />
          </el-select>
        </el-form-item>

        <!-- 动态字段表单 -->
        <template v-if="form.modelType && modelFields.length">
          <el-divider content-position="center">
            {{ modelTypeOptions.find((item) => item.value === form.modelType)?.label || '-' }}信息
          </el-divider>
          <template v-for="field in sortedModelFields" :key="field.fieldKey">
            <el-form-item
              :label="field.fieldName"
              :prop="'customFields.' + field.fieldKey"
              :rules="field.required ? [{ required: true, message: `请输入${field.fieldName}`, trigger: 'blur' }] : []"
            >
              <!-- 文本输入 -->
              <el-input v-if="field.fieldType === 'text'" v-model="form.customFields[field.fieldKey]" :placeholder="`请输入${field.fieldName}`" />

              <!-- 文本域 -->
              <template v-else-if="field.fieldType.toLowerCase() === 'textarea'">
                <el-input
                  v-model="form.customFields[field.fieldKey]"
                  type="textarea"
                  :rows="4"
                  :placeholder="`请输入${field.fieldName}`"
                />
              </template>

              <!-- 富文本编辑器 -->
              <editor v-else-if="field.fieldType === 'editor'" v-model="form.customFields[field.fieldKey]" :min-height="192" />

              <!-- 图片上传 -->
              <image-upload v-else-if="field.fieldType === 'image'" v-model="form.customFields[field.fieldKey]" :limit="5" multiple />

              <!-- 图片集 -->
              <template v-else-if="field.fieldType === 'gallery'">
                <image-upload
                  v-model="form.customFields[field.fieldKey]"
                  :limit="5"
                  multiple
                  :file-type="['png', 'jpg', 'jpeg', 'gif']"
                  list-type="picture-card"
                />
              </template>

              <!-- 视频上传 -->
              <file-upload v-else-if="field.fieldType === 'video'" v-model="form.customFields[field.fieldKey]" :limit="1" accept="video/*" />

              <!-- JSON 键值对编辑器 -->
              <template v-else-if="field.fieldType.toLowerCase() === 'json'">
                <div class="json-editor">
                  <div v-for="(item, index) in getJsonArray(field.fieldKey)" :key="index" class="json-item mb-[10px]">
                    <el-row :gutter="10">
                      <el-col :span="8">
                        <el-input v-model="item.key" placeholder="键名" @change="updateJsonField(field.fieldKey)" />
                      </el-col>
                      <el-col :span="12">
                        <el-input v-model="item.value" placeholder="值" @change="updateJsonField(field.fieldKey)" />
                      </el-col>
                      <el-col :span="4">
                        <el-button type="danger" link @click="removeJsonItem(field.fieldKey, index)">
                          <el-icon><Delete /></el-icon>
                        </el-button>
                      </el-col>
                    </el-row>
                  </div>
                  <el-button type="primary" link @click="addJsonItem(field.fieldKey)">
                    <el-icon><Plus /></el-icon>添加键值对
                  </el-button>
                </div>
              </template>
            </el-form-item>
          </template>
        </template>

        <!-- 发布信息 -->
        <el-divider content-position="center">发布信息</el-divider>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="作者" prop="author">
              <el-input v-model="form.author" placeholder="请输入作者" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="发布时间" prop="publishTime">
              <el-date-picker
                v-model="form.publishTime"
                type="datetime"
                clearable
                value-format="YYYY-MM-DD HH:mm:ss"
                placeholder="请选择发布时间"
                class="w-[100%]"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="文章状态" prop="status">
              <el-select v-model="form.status" placeholder="请选择状态" class="w-[100%]">
                <el-option v-for="dict in cms_article_status" :key="dict.value" :label="dict.label" :value="dict.value" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="推荐类型" prop="isTop">
              <el-select v-model="form.isTop" placeholder="请选择推荐类型" class="w-[100%]">
                <el-option label="普通" value="0" />
                <el-option label="置顶" value="1" />
                <el-option label="推荐" value="2" />
                <el-option label="置顶且推荐" value="3" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <!-- SEO设置 -->
        <el-divider content-position="center">SEO设置</el-divider>
        <el-form-item label="SEO标题" prop="seoTitle">
          <el-input v-model="form.seoTitle" placeholder="请输入SEO标题" />
        </el-form-item>
        <el-form-item label="SEO关键词" prop="seoKeywords">
          <el-input v-model="form.seoKeywords" placeholder="请输入SEO关键词" />
        </el-form-item>
        <el-form-item label="SEO描述" prop="seoDescription">
          <el-input v-model="form.seoDescription" type="textarea" placeholder="请输入SEO描述" />
        </el-form-item>

        <!-- 高级设置 -->
        <!-- <el-divider content-position="center">高级设置</el-divider>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="允许评论" prop="allowComment">
              <el-radio-group v-model="form.allowComment">
                <el-radio :label="1">是</el-radio>
                <el-radio :label="0">否</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="排序号" prop="sort">
              <el-input-number v-model="form.sort" :min="0" controls-position="right" class="w-[100%]" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入备注" />
        </el-form-item> -->
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Article" lang="ts">
import { listArticle, getArticle, delArticle, addArticle, updateArticle } from '@/api/cms/article';
import { ArticleVO, ArticleQuery, ArticleForm } from '@/api/cms/article/types';
import { listArticleCategory } from '@/api/cms/articleCategory';
import { ArticleCategoryVO } from '@/api/cms/articleCategory/types';
import { ModelType, FieldType } from '@/api/cms/model/types';
import { listModel, getModel } from '@/api/cms/model';
import { listModelField, getModelField } from '@/api/cms/modelField';
import { baseFields } from '@/api/cms/model/config';
import { listCategory } from '@/api/cms/category';
import type { CategoryVO } from '@/api/cms/category/types';
import { Plus, Delete } from '@element-plus/icons-vue';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { cms_article_status } = toRefs<any>(proxy?.useDict('cms_article_status'));
const articleList = ref<ArticleVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);

const queryFormRef = ref<ElFormInstance>();
const articleFormRef = ref<ElFormInstance>();

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const initFormData: ArticleForm = {
  id: undefined,
  modelType: undefined,
  title: undefined,
  slug: undefined,
  categoryId: undefined,
  author: undefined,
  publishTime: undefined,
  isTop: '0',
  status: '0',
  template: 'default',
  allowComment: 1,
  sort: 0,
  customFields: {}
};
const data = reactive<PageData<ArticleForm, ArticleQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    title: undefined,
    slug: undefined,
    categoryId: undefined,
    author: undefined,
    publishTime: undefined,
    status: undefined,
    isTop: undefined,
    modelType: undefined,
    params: {
      beginTime: undefined,
      endTime: undefined
    }
  },
  rules: {
    modelType: [{ required: true, message: '请选择内容类型', trigger: 'change' }],
    title: [{ required: true, message: '文章标题不能为空', trigger: 'blur' }],
    slug: [{ required: true, message: 'URL别名不能为空', trigger: 'blur' }],
    categoryId: [{ required: true, message: '请选择所属分类', trigger: 'change' }],
    status: [{ required: true, message: '请选择文章状态', trigger: 'change' }]
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询CMS文章列表 */
const getList = async () => {
  loading.value = true;
  const res = await listArticle(queryParams.value);
  articleList.value = res.rows;
  total.value = res.total;
  loading.value = false;
};

/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
};

/** 表单重置 */
const reset = () => {
  form.value = { ...initFormData };
  articleFormRef.value?.resetFields();
};

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  queryParams.value.params.beginTime = dateRange.value?.[0];
  queryParams.value.params.endTime = dateRange.value?.[1];
  getList();
};

/** 重置按钮操作 */
const resetQuery = () => {
  dateRange.value = undefined;
  queryFormRef.value?.resetFields();
  handleQuery();
};

/** 多选框选中数据 */
const handleSelectionChange = (selection: ArticleVO[]) => {
  ids.value = selection.map((item) => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
};

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  dialog.visible = true;
  dialog.title = '添加CMS文章';
};

/** 修改按钮操作 */
const handleUpdate = async (row?: ArticleVO) => {
  const _id = row?.id || ids.value[0];
  const res = await getArticle(_id);
  const articleData = res.data;

  // 先设置模型类型
  form.value.modelType = articleData.modelType;

  // 获取对应的字段配置
  if (articleData.modelType) {
    await handleModelTypeChange(articleData.modelType);
  }

  // 然后处理自定义字段
  if (articleData.customFields) {
    try {
      const parsedFields = typeof articleData.customFields === 'string' ? JSON.parse(articleData.customFields) : articleData.customFields;

      // 处理JSON类型字段
      Object.keys(parsedFields).forEach((key) => {
        const field = modelFields.value.find((f) => f.fieldKey === key);

        if (field?.fieldType === 'json') {
          const jsonObject = parsedFields[key];
          form.value.customFields[key] = Object.entries(jsonObject).map(([key, value]) => ({
            key,
            value
          }));
        } else {
          form.value.customFields[key] = parsedFields[key];
        }
      });
    } catch (error) {
      console.error('解析自定义字段失败:', error);
      form.value.customFields = {};
    }
  }

  // 设置其他表单字段
  Object.assign(form.value, {
    ...articleData,
    customFields: form.value.customFields // 保持自定义字段不被覆盖
  });

  dialog.visible = true;
  dialog.title = '修改文章';
};

/** 处理自定义字段 */
const handleCustomFields = (formData: any) => {
  const customFields = {};

  modelFields.value.forEach((field) => {
    const value = formData.customFields[field.fieldKey];
    if (value !== undefined && value !== '') {
      switch (field.fieldType) {
        case 'json':
          // 处理JSON类型字段
          const jsonArray = getJsonArray(field.fieldKey);
          const jsonObject = {};
          jsonArray.forEach((item) => {
            if (item.key) {
              jsonObject[item.key] = item.value;
            }
          });
          customFields[field.fieldKey] = jsonObject;
          break;
        // ... 其他case保持不变
        default:
          customFields[field.fieldKey] = value;
      }
    }
  });

  return customFields;
};

/** 在提交表单前生成 URL */
const generateUrl = (data: any, model: any) => {
  // 如果没有模型或URL规则，返回空字符串
  if (!model || !model.urlRule) {
    return '';
  }

  const date = data.publishTime ? new Date(data.publishTime) : new Date();
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');

  let url = model.urlRule
    .replace('{year}', year.toString())
    .replace('{month}', month)
    .replace('{day}', day)
    .replace('{id}', data.id || '')
    .replace('{slug}', data.slug || '')
    .replace('{category}', data.categorySlug || '');

  return url + '.html';
};

/** 提交按钮 */
const submitForm = () => {
  articleFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      try {
        // 处理自定义字段
        const customFields = handleCustomFields(form.value);
        const submitData = {
          ...form.value,
          customFields: JSON.stringify(customFields),
          url: currentModel.value ? generateUrl(form.value, currentModel.value) : '' // 添加空值检查
        };

        if (submitData.id) {
          await updateArticle(submitData);
        } else {
          await addArticle(submitData);
        }
        proxy?.$modal.msgSuccess('操作成功');
        dialog.visible = false;
        await getList();
      } finally {
        buttonLoading.value = false;
      }
    }
  });
};

/** 删除按钮操作 */
const handleDelete = async (row?: ArticleVO) => {
  const _ids = row?.id || ids.value;
  await proxy?.$modal.confirm('是否确认删除CMS文章编号为"' + _ids + '"的数据项？').finally(() => (loading.value = false));
  await delArticle(_ids);
  proxy?.$modal.msgSuccess('删除成功');
  await getList();
};

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download(
    'cms/article/export',
    {
      ...queryParams.value
    },
    `article_${new Date().getTime()}.xlsx`
  );
};

// 分类选项
const categoryOptions = ref<CategoryVO[]>([]);

/** 获取分类列表 */
const getCategoryOptions = async () => {
  try {
    const res = await listCategory();
    categoryOptions.value = res.rows;
  } catch (error) {
    console.error('获取分类列表失败:', error);
  }
};

// 添加响应式数据
const modelFields = ref<ModelField[]>([]);
const modelTypeOptions = ref<{ label: string; value: ModelType }[]>([]);
const currentModel = ref<any>(null); // 当前选中的模型

// 获取所有启用的内容模型
const getModelTypeOptions = async () => {
  try {
    const res = await listModel();
    if (res.code === 200 && res.rows) {
      // 确保有数据
      modelTypeOptions.value = res.rows.map((model) => ({
        label: model.modelName,
        value: model.modelType
      }));
    }
  } catch (error) {
    console.error('获取内容模型失败:', error);
    proxy?.$modal.msgError('获取内容模型失败');
  }
};

// 处理模型类型变化
const handleModelTypeChange = async (type: string) => {
  if (!type) {
    modelFields.value = [];
    form.value.customFields = {};
    currentModel.value = null;
    return;
  }

  try {
    // 先获取模型列表，找到对应type的模型id
    const modelListRes = await listModel();
    if (modelListRes.code === 200 && modelListRes.rows) {
      const model = modelListRes.rows.find((m) => m.modelType === type);
      if (model) {
        // 使用模型ID获取详细信息
        const modelRes = await getModel(model.id);
        if (modelRes.code === 200) {
          currentModel.value = modelRes.data;
        }
      }
    }

    // 获取字段列表
    const fieldRes = await listModelField({ modelType: type });
    if (fieldRes.code === 200 && fieldRes.rows) {
      modelFields.value = fieldRes.rows;
      
      // 添加详细的字段类型日志
      modelFields.value.forEach(field => {
        console.log(`Field: ${field.fieldKey}, Type: ${field.fieldType}, Expected: ${FieldType[field.fieldType.toUpperCase()]}`);
      });

      // 如果是编辑状态，保留已有的值
      if (!form.value.id) {
        form.value.customFields = {};
        modelFields.value.forEach((field) => {
          if (field.defaultValue !== undefined) {
            form.value.customFields[field.fieldKey] = field.defaultValue;
          }
        });
      }
    }
  } catch (error) {
    console.error('获取模型字段失败:', error);
    proxy?.$modal.msgError('获取模型字段失败');
  }
};

// JSON编辑器相关方法
const getJsonArray = (fieldKey: string) => {
  if (!form.value.customFields[fieldKey]) {
    form.value.customFields[fieldKey] = [];
  }
  return form.value.customFields[fieldKey];
};

const addJsonItem = (fieldKey: string) => {
  const jsonArray = getJsonArray(fieldKey);
  jsonArray.push({ key: '', value: '' });
};

const removeJsonItem = (fieldKey: string, index: number) => {
  const jsonArray = getJsonArray(fieldKey);
  jsonArray.splice(index, 1);
  updateJsonField(fieldKey);
};

const updateJsonField = (fieldKey: string) => {
  const jsonArray = getJsonArray(fieldKey);
  const jsonObject = {};
  jsonArray.forEach((item) => {
    if (item.key) {
      jsonObject[item.key] = item.value;
    }
  });
  // 在提交时会用到这个转换后的对象
  form.value.customFields[`${fieldKey}_object`] = jsonObject;
};

// 在 script setup 中添加 dateRange 的定义
const dateRange = ref<[string, string]>();

// 添加计算属性对字段进行排序
const sortedModelFields = computed(() => {
  return [...modelFields.value].sort((a, b) => {
    // 首先按照 sort 字段排序
    if (a.sort !== b.sort) {
      return b.sort - a.sort;  // 数字大的排在前面
    }
    // 如果 sort 相同，则按照 fieldKey 字母顺序排序
    return a.fieldKey.localeCompare(b.fieldKey);
  });
});

onMounted(() => {
  getList();
  getCategoryOptions();
  getModelTypeOptions();
});
</script>

<style lang="scss" scoped>
.json-editor {
  .json-item {
    display: flex;
    align-items: center;
    margin-bottom: 8px;

    .el-button {
      margin-left: 8px;
    }
  }
}
</style>
